//
//  CZComposeViewController.swift
//  WHWeiBo01
//
//  Created by whitcast on 16/7/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD


class CZComposeViewController: UIViewController {

    // MARK:    -懒加载控件
    private lazy var titleLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        
       
        label.numberOfLines = 0
        label.textAlignment = .Center
        //  获取用户名
        if let name = CZUserAccountViewModel.shareUserAccount.userAccount?.name {
            
            
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            // 获取名字的范围
            let range = (title as NSString).rangeOfString(name)
            
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            label.attributedText = attributeStr
        } else {
            label.text = "发微博"
        }
        
        
        
        label.sizeToFit()
        
        return label
    
    }()
    //  右侧按钮(发送按钮)
    private lazy var rightButton: UIButton = {
    
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.size = CGSize(width: 45, height: 30)
        //  因为button被UIBarButtonItem,这样设置没有作用
//        button.enabled = false
        return button
        
    }()
    
    //  添加自定义Textview
    private lazy var textView: CZComposeTextView = {
        let view = CZComposeTextView()
        view.delegate = self
        view.placeHolder = "别低头,绿帽会掉~别低头,绿帽会掉~别低头,绿帽会掉~别低头"
        view.font = UIFont.systemFontOfSize(15)
        //  垂直方向开启弹簧效果
        view.alwaysBounceVertical = true
        return view
    
    }()
    //  toolbar
    private lazy var toolBar: CZComposeToolBar = {
        let view = CZComposeToolBar(frame: CGRectZero)
        return view
    
    }()
    //  配图
    private lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        return view
        
    }()
    //  表情键盘
    private lazy var keyBoard: CZEmoticonKeyBoard = {
        let view = CZEmoticonKeyBoard()
        //  设置视图大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    private func setupUI() {
        
        //  监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //  监听表情按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSeletedEmotionButtonNotification, object: nil)
        //  监听删除表情按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelecteDeleteEmoticonButtonNotification, object: nil)
    
        setupNavUI()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(30)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        //  设置闭包
        toolBar.selectedToolBarButtonClosure = { [weak self] (type: CZComposeToolBarButtonType) in
          
            switch type {
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .Add:
                print("加号")
            }
            
        
        }
        
        pictureView.didSelectedAddClosure = { [weak self] in
            //  打开图片选择器
            self?.didSelectedPicture()
        }
        
        
    
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    // MARK:    -- 监听删除表情按钮点击的通知
    @objc private func didSelectedDeleteEmoticon() {
        //  删除内容
        textView.deleteBackward()
    
    }
    
    
    // MARK:    --  监听表情按钮点击的通知
    @objc private func didSelectedEmoticon(noti: NSNotification) {
    
        let emoticon = noti.object as! CZEmoticon
        textView.insertEmoticon(emoticon)
       
        //  代码已经抽取到CZComposeTextView+Extension分类中
//        //  图片
//        if emoticon.type == "0" {
////            //  获取表情描述
////            let chs = emoticon.chs!
////            //  插入内容
////            textView.insertText(chs)
//            
//            //  记录上一次的富文本
//            let originalAttributedStr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            //  1. 获取表情按钮的对应的表情图片
//            let image = UIImage(named: emoticon.path!)
//            //  2. 通过UIImage创建一个文本附件(NSTextAttachment)
//            let attachment = NSTextAttachment()
//            attachment.image = image
//            //  获取行高,指定大小
//            let fontHeight = textView.font!.lineHeight
//            //  设置图片大小
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            //  3.通过NSTextAttachment创建富文本(NSAttributedString)
//            let attributedStr = NSAttributedString(attachment: attachment)
//            
//            //  4.给我们的textview设置富文本(attributedText)
////            originalAttributedStr.appendAttributedString(attributedStr)
//            //  获取textview的选中范围
//            var range = textView.selectedRange
//            
//            //  根据指定范围替换想要的富文本
//            originalAttributedStr.replaceCharactersInRange(range, withAttributedString: attributedStr)
//            
//            
//            
//            //  5. 指定富文本字体大小
//            originalAttributedStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originalAttributedStr.length))
//            
//            textView.attributedText = originalAttributedStr
//            //  每次点击让其光标位置加1, 设置其选中范围的长度为0
//            range.location += 1; range.length = 0
//            //  根据选中的范围设置光标的位置
//            textView.selectedRange = range
//            
//            
//        
//        } else {
//            //  emoji
//            let emoji = (emoticon.code! as NSString).emoji()
//            //
//            textView.insertText(emoji)
//        }
        

        
    
    }
    
    // MARK:    --  监听键盘frame改变的事件
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        
        
        //  获取屏幕的frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //  获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //  更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        
        //  执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    
    }
    
    
    // MARK: -- 点击事件处理
    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    //  发送微博
    @objc private func sendAction() {
        
//        //  根据指定的范围,遍历我们的富文本
//        //  infoDic - 表示遍历到内容
//        //  range  - 表示遍历到范围
//        //  stop   - 是否停止      a.memory = true
//        var result = ""
//        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (infoDic, range, _) -> Void in
//            
//            
////            print(infoDic["NSAttachment"])
//            
//            if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
//                //  有图片
//
//                let chs = attachment.emoticon!.chs!
//                //  拼接表情描述
//                result += chs
//                
//            } else {
//                //  文字
//                //  获取指定范围内的文字
//                let text = self.textView.attributedText.attributedSubstringFromRange(range).string
//                result += text
//
//            }
//
//        }
//        print(result)
        
       
        
        //  带图片微博上传接口
        if pictureView.images.count > 0 {
            //  带图片微博上传接口
            upload()
//            let image = pictureView.images.first!
//            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
//            //  获取富文本对应的字符串
//            let text = textView.emoticonString //textView.text!
//            SVProgressHUD.show()
//            CZNetworkTools.sharedToos.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
//                if error != nil {
//                    print(error)
//                    SVProgressHUD.showErrorWithStatus("发送失败")
//                    return
//                }else {
//                    //  发送成功
//                    SVProgressHUD.showSuccessWithStatus("发送成功")
//                }
//            })
        } else {
            //  发送文字微博接口
            update()
//            //  发送文字微博接口
//            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
//            //  获取富文本对应的字符串
//            let text = textView.emoticonString //textView.text!
//            SVProgressHUD.show()
//            CZNetworkTools.sharedToos.update(accessToken, status: text) { (response, error) -> () in
//                if error != nil {
//                    print(error)
//                    SVProgressHUD.showErrorWithStatus("发送失败")
//                    return
//                }
//    
//                
//                //  发送成功
//                SVProgressHUD.showSuccessWithStatus("发送成功")
//            }
        }
       
        

        
    }
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //  上传图片微博即可
    private func upload() {
        let image = pictureView.images.first!
        let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
        //  获取富文本对应的字符串
        let text = textView.emoticonString //textView.text!
        SVProgressHUD.show()
        CZNetworkTools.sharedToos.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }else {
                //  发送成功
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
        })
    
    }
    
    //  发送文字微博接口
    private func update() {
    
        //  发送文字微博接口
        let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
        //  获取富文本对应的字符串
        let text = textView.emoticonString //textView.text!
        SVProgressHUD.show()
        CZNetworkTools.sharedToos.update(accessToken, status: text) { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            
            //  发送成功
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }

    }
 

}
//  处理toolbar按钮点击的逻辑
extension CZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  表情键盘处理
    func didSelectedEmoticon() {
        //  显示表情键盘或者系统键盘
        if textView.inputView == nil {
            //  设置inputView 表情键盘
        
            textView.inputView = keyBoard
            //  设置键盘显示的icon
            toolBar.showEmotionIcon(true)
        } else {
            //  设置成系统键盘
            textView.inputView = nil
            //  设置键盘显示的icon
            toolBar.showEmotionIcon(false)
        }
     
        //  获取第一响应者
        textView.becomeFirstResponder()
        //  重新刷新inputview
        textView.reloadInputViews()
        
    }
    
    
    //  图片处理
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        //  设置代理
        imagePictureCtr.delegate = self
        //  判断是否支持这个来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePictureCtr.sourceType = .Camera
            print("支持相机")
        } else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机,使用的图库")
        }
        
        //  判断是否支持前置或者后者摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持后置摄像头")
        } else {
            print("前后置摄像头不支持")
        }
        //  允许用户编辑
        //imagePictureCtr.allowsEditing = true
        
        presentViewController(imagePictureCtr, animated: true, completion: nil)
        
        
    
    }
    //  获取选中的图片 , 如果实现了协议就不会自己调用dismissViewControllerAnimated
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    
        //  获取压缩后的图片
        let scaleImage = image.scaleImageWithScaleWidth(200)
        print(scaleImage)
       
        pictureView.addImage(scaleImage)
        
     
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
//    /**
//     根据指定压缩后的宽度,压缩图片
//     
//     - parameter width: 压缩的宽度
//     - parameter image: 需要压缩的图片
//     
//     - returns:   压缩后的图片
//     */
//    private func scaleImageWithScaleWidth(scaleWidth: CGFloat, image: UIImage) -> UIImage {
//    
//        //  根据压缩后的宽度计算压缩后的高度
//        let scaleHeight = scaleWidth / image.size.width * image.size.height
//        
//        //  压缩后的大小
//        let size = CGSize(width: scaleWidth, height: scaleHeight)
//        //  开启上下文
//        UIGraphicsBeginImageContext(size)
//        
//        //  把图片渲染到指定范围内
//        image.drawInRect(CGRect(origin: CGPointZero, size: size))
//        //  获取上下文中压缩后的图片
//        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
//        
//        //  关闭上下文
//        UIGraphicsEndImageContext()
//        
//        return scaleImage
//        
//    }
    
    
    
    
    
    
}


extension CZComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //  根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }

}






